<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <style>
      #field {
        width: 200px;
        height: 150px;
        border: 10px solid black;
        background-color: #00ff00;
        overflow: hidden;
      }

      #ball {
        position: fixed;
        transition: all 0.4s;
        transform: translate(-50%, -50%);
      }
    </style>
  </head>

  <body style="height: 2000px">
    Click on a field to move the ball there.
    <br />
    The ball should never leave the field.

    <div id="field">
      <img src="https://en.js.cx/clipart/ball.svg" id="ball" /> . . . . . . . .
      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
      . . . . . . . . . . . . . . . . . . . . .
    </div>
    <script>
      let ball = document.getElementById("ball");
      let field = document.getElementById("field");
      const handleFieldClick = function (e) {
        const rect = field.getBoundingClientRect();
        const bs = getComputedStyle(ball);

        const ballWidth = parseInt(bs.width);
        const ballHeight = parseInt(bs.height);

        const fs = getComputedStyle(field);
        const { left, top, width, height } = rect;
        const { borderWidth } = fs;
        const bw = parseInt(borderWidth);

        // console.log(left, top, width, height, bw)

        const minX = left + bw + ballWidth / 2;
        const maxX = left + bw + width - ballWidth;

        const minY = top + bw + ballHeight / 2;
        const maxY = top + bw + height - ballHeight;
        let x = e.clientX;
        let y = e.clientY;
        if (x < minX) {
          x = minX;
        }
        if (x > maxX) {
          x = maxX;
        }
        if (y < minY) {
          y = minY;
        }
        if (y > maxY) {
          y = maxY;
        }

        ball.style.top = `${y}px`;
        ball.style.left = `${x}px`;
        console.log(x, y, minX, minY, maxX, maxY);
      };
      field.addEventListener("click", handleFieldClick);
    </script>
  </body>
</html>
